package org.example.web;

import org.example.vo.Result;
import org.example.vo.UploadInfo;
import org.example.vo.UploadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/2
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
public class UploadDo {

    @Autowired
    UploadProperties uploadProperties;

    // upload/image/a/b/c
    // upload/doc
    @PostMapping("upload/**")
    public Result upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request) throws IOException {
        // upload/image/a/b/c
        String path = request.getServletPath();
        String webPath = path.substring("/upload".length()) + "/**";
        System.out.println("webPath = " + webPath);

        UploadInfo uInfo = uploadProperties.getMapper()
                .stream()
                .filter(uploadInfo -> uploadInfo.getWebPath().equals(webPath))
                .findFirst()
                .get();

        String newName = UUID.randomUUID().toString();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        if (uInfo.getSuffix().contains(suffix.substring(1)) == false) {
            return new Result(0,"文件类型错误: " + suffix,null);
        }

        // 创建磁盘路径
        File dir = new File(uInfo.getDiskPath().substring("file:".length()));
        if (dir.exists()==false) {
            dir.mkdirs();
        }

        File fileObj = new File(uInfo.getDiskPath().substring(5) + newName + suffix);
        file.transferTo(fileObj);
        // 单文件上传
        return Result.ok("文件上传成功!",webPath.substring(0,webPath.length()-3)+"/"+newName+suffix);
    }

    //  remove/image/xxxx.png
    @PostMapping("remove/**")
    public Result upload(HttpServletRequest request){
        // TODO 请实现文件删除功能!
        return Result.ok("文件删除成功!",null);
    }

}
